<template>
  <div class="header-container">
    <nav-bar
      :title="'地址管理'"
      :showLeftArrow="true"
      :leftText="'返回'"
      @click-left="back"
    >
    </nav-bar>
  </div>
  <div class="main-container">
    <van-address-list
      v-model="chosenAddrId"
      :list="vantAddrList"
      @add="onAdd"
      @edit="onEdit"
      :switchable="addrSwitchable"
      @select="onSelect"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import NavBar from "@/components/NavBar.vue";
import TabBar from "@/components/TabBar.vue";
import { useRoute, useRouter } from "vue-router";
import { AxiosError } from "axios";
import { Toast, AddressListAddress } from "vant";
import addressService from "@/services/address.service";
import UmsAddress from "@/entity/UmsAddress";
import OperationType from "@/entity/OperationType";

type StateType = {
  addrList: UmsAddress[];
  chosenAddrId: number | string;
  addrSwitchable: boolean;
  vantAddrList: AddressListAddress[];
  from?: "OrderPreview";
};

export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive<StateType>({
      addrList: [],
      addrSwitchable: false,
      chosenAddrId: -1,
      vantAddrList: [],
    });

    onMounted(async () => {
      if (route.query.from != null && route.query.from == "OrderPreview") {
        state.from = route.query.from;
        state.addrSwitchable = true;
        if (route.query.addressId != null) {
          state.chosenAddrId = Number(route.query.addressId);
        }
      }
      load();
    });

    const load = async () => {
      try {
        const addresses = await addressService.list();
        state.addrList = addresses;
        if (state.addrList) {
          state.vantAddrList = state.addrList.map((it) => {
            const addr: AddressListAddress = {
              id: it.id != null ? it.id : 0,
              tel: it.receiverPhone != null ? it.receiverPhone : "",
              name: it.receiverName != null ? it.receiverName : "",
              address:
                it.receiverAddress != null
                  ? `${it.receiverProvince}${it.receiverCity}${it.receiverAddress}`
                  : "",
              isDefault: false,
            };

            return addr;
          });
          if (
            state.chosenAddrId == null &&
            state.vantAddrList &&
            state.vantAddrList.length > 0
          ) {
            state.chosenAddrId = state.vantAddrList[0].id;
          }
        }
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const back = () => {
      router.back();
    };

    const onAdd = () => {
      router.push({
        path: "/address-detail",
        query: {
          ...route.query,
          operation: OperationType.CREATE,
        },
      });
    };
    const onEdit = (item: AddressListAddress, index: number) => {
      router.push({
        path: "/address-detail",
        query: {
          ...route.query,
          operation: OperationType.EDIT,
          id: item.id,
        },
      });
    };

    const onSelect = (item: AddressListAddress, index: number) => {
      if (state.from == null) {
        return;
      }
      const query = {
        ...route.query,
      };
      query.addressId = String(item.id);
      delete query.from;

      router.push({
        path: "/order-preview",
        query: query,
      });
    };

    return {
      ...toRefs(state),
      back,
      onAdd,
      onEdit,
      onSelect,
    };
  },
});
</script>

<style scoped></style>
